//
//  SelectExamPlaceViewController.m
//  CommunityNannyO2O
//
//  Created by 90 on 15/7/21.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "SelectExamPlaceViewController.h"
#import "AppConfig.h"
#import "QXNetWorkTool.h"
#import "APIAdress.h"
#import "MBProgressHUD+YC.h"
#import "MJExtension.h"
#import "AccountTool.h"
#import "SelectExamPlaceCell.h"
#import "CreateSignUpTableController.h"
#import "SearchData.h"
#import "SearchCityViewController.h"
#import "UserDataSingleton.h"
#import "CityDataModel.h"
#import "MJRefresh.h"
#import "ClubListModel.h"
#import "CitylistModel.h"

@interface SelectExamPlaceViewController()<QXNetWorkToolDelegate,
UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,SelectExamCityDeletage,UIGestureRecognizerDelegate>
{
    
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UILabel *curCityLabel;

@property (strong, nonatomic)NSMutableArray *data;
@property (strong, nonatomic)NSMutableArray *showData;
@property (copy, nonatomic) NSString *cityId;
@property (copy, nonatomic) NSString *curCityId;
@property (copy, nonatomic) NSString *searchText;

@property (assign,nonatomic) int pageNum;

@end


@implementation SelectExamPlaceViewController

//@synthesize showData;
@synthesize data;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.dataSource = self;
    
    self.tableView.delegate = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.showsVerticalScrollIndicator = FALSE;
    
    self.tableView.showsHorizontalScrollIndicator = FALSE;
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    self.searchBar.delegate = self;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_select_exam_place_search_bar.png"]];
    
    self.searchBar.backgroundImage = imageView.image;
    
    
    [self.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"bg_select_exam_place_search_bar_textfield"]
                                         forState:UIControlStateNormal];
    
    [self.searchBar setImage:[UIImage imageNamed:@"ico_select_exam_place_search_bar"]
            forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    
    
    self.data = [[NSMutableArray alloc] init];
    self.showData = [[NSMutableArray alloc] init];
    
    _pageNum = 1;
    
    self.cityId = [UserDataSingleton shareInstance].curCityId;
    self.curCityId = [UserDataSingleton shareInstance].curCityId;
    self.curCityLabel.text = [UserDataSingleton shareInstance].cityName;
    
    [self getDataCityId:self.cityId ExamSiteName:@""];
    
    self.searchText = @"";
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    
    [self.view addGestureRecognizer:tapGestureRecognizer];
    tapGestureRecognizer.delegate = self;
}

-(void)tap
{
    [self.searchBar resignFirstResponder];
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"])
    {
        //如果当前是tableView
        //做自己想做的事
        return NO;
    }
    return YES;
}


- (void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    switch (tag)
    {
        case 1:
        {
            //俱乐部列表
            for (NSDictionary * dic in Response)
            {
                ClubListModel *model = [ClubListModel ClubListWithDict:dic];
                
                //全国搜索
                if ([self.curCityId isEqualToString:@""])
                {
                    [self.showData addObject:model];
                }
                else  //系那是当前城市数据
                {
                    [self.data addObject:model];
                    [self.showData addObject:model];
                }
            }
            
            [self.tableView reloadData];
            
            break;
        }
    }
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    NSString *mes = message;
    
    [MBProgressHUD showSuccess:mes toView:self.view];
}

- (void)GetFailResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    NSString *message = Response;
    
    [MBProgressHUD showError:message toView:self.view];
}

-(void)getDataCityId:(NSString *)city_id
        ExamSiteName:(NSString *)exam_site_name
{
    [MBProgressHUD showMessage:@"正在加载" toView:self.view];
    
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
    NSString *pagenum = [NSString stringWithFormat:@"%d",_pageNum];
    
    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:ExamClubListInterface andParameter:@[@{
                                                                                                            @"club_city":city_id,
                                                                                                            @"site_name":exam_site_name,
                                                                                                            @"nowpage":pagenum,
                                                                                                            @"pagesize":@"10"}] tag:1];
}

#pragma mark 设置上下拉刷新

- (void)loadNewData
{
    [self.showData removeAllObjects];
    
    if (![self.curCityId isEqualToString:@""])
    {
        [self.data removeAllObjects];
    }
    
    _pageNum = 1;
    
    [self getDataCityId:self.curCityId ExamSiteName:self.searchText];
    
    [self.tableView.header endRefreshing];
}

- (void)loadMoreData
{
    ++_pageNum;
    
    [self getDataCityId:self.curCityId
           ExamSiteName:self.searchText];
    
    [self.tableView.footer endRefreshing];
}

//tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.showData count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 71;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.showData count] > 0)
    {
        SelectExamPlaceCell *cell = [SelectExamPlaceCell cellWithTableView:tableView];
        
        ClubListModel *model = (ClubListModel *)[self.showData objectAtIndex:indexPath.row];
        cell.title.text = model.exam_site_name;
        cell.address.text = model.address;
        
        return cell;
    }
    
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if ([self.showData count] > 0)
    {
        ClubListModel *model = [self.showData objectAtIndex:indexPath.row];
        NSString *string = [self.curCityLabel.text stringByAppendingString:model.address];
        
        if ([self.delegate respondsToSelector:@selector(setExamPlace:Id:)]) {
            
            [self.delegate setExamPlace:string Id:model.id];
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (NSMutableArray *)searchStringForcharacter:(NSString*)searchStr
{
    NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:10];
    
    for (int i = 0; i < [self.data count]; ++i)
    {
        ClubListModel *model = (ClubListModel *)[self.data objectAtIndex:i];
        
        if ([model.exam_site_name hasPrefix:searchStr])
        {
            [tmp addObject:model];
        }
    }
    
    return [tmp count] > 0 ? tmp : nil;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    self.searchText = searchBar.text;
    
    if (self.searchText != nil && self.searchText.length > 0)
    {
        [self.showData removeAllObjects];
        _pageNum = 1;
        self.curCityId = @"";
        [self getDataCityId:self.curCityId ExamSiteName:self.searchText];
    }
    else
    {
        self.curCityId = self.cityId;
        self.showData = [NSMutableArray arrayWithArray:self.data];
        [self.tableView reloadData];
    }
}


//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
//{
//    if (searchText != nil && searchText.length > 0)
//    {
////        self.showData = [self searchStringForcharacter:searchText];
////        
////        if (!self.showData)
////        {
////            self.showData = [NSMutableArray arrayWithCapacity:1];
////            //            [self.showData addObject:@""];
////        }
//        
//        _pageNum = 1;
//        self.curCityId = @"";
//        [self getDataCityId:self.curCityId ExamSiteName:searchText];
//    }
//    else
//    {
//        self.curCityId = self.cityId;
//        self.showData = [NSMutableArray arrayWithArray:self.data];
//        [self.tableView reloadData];
//    }
//}

-(void)configNavigationItem
{
    self.navigationItem.title = @"选择考试地点";
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.navigationController.navigationBar
     setBackgroundImage:[UIImage imageNamed:@"bg_navigation_bar"]
     forBarMetrics:UIBarMetricsDefault];
    
    //status bar的字体为白色
    //导航栏的背景色是黑色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],NSFontAttributeName,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self configNavigationRightItemWith:[UIImage imageNamed:@"ico_select_exam_place_locate_city"] andAction:^{
        
        SearchCityViewController *obj = [SearchCityViewController create];
        obj.delegate = self;
        
        [self.navigationController pushViewController:obj animated:YES];
    }];
}

-(void)setExamCity:(NSString *)city
{
    self.curCityLabel.text = city;
    
    NSMutableArray *data1 = [UserDataSingleton shareInstance].cityList;
    
    for (int i = 0; i < [data1 count]; ++i)
    {
        CitylistModel *model = [data1 objectAtIndex:i];
        
        if (model && [model.name isEqualToString:city])
        {
//            if (![self.cityId isEqualToString:model.id])
            {
                [self.data removeAllObjects];
                [self.showData removeAllObjects];
            }
            
            self.cityId = model.id;
            self.curCityId = model.id;
            
            _pageNum = 1;
            
            [self getDataCityId:self.cityId ExamSiteName:@""];
            
            break;
        }
    }
}

-(void)useMethodToFindBlackLineAndHind
{
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    blackLineImageView.hidden = YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self configNavigationItem];
    
    [self useMethodToFindBlackLineAndHind];
}

-(void)viewWillDisappear:(BOOL)animated
{
    
}

@end


/*
@interface SelectExamPlaceViewController()<QXNetWorkToolDelegate,
        UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,SelectExamCityDeletage>
{

}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UILabel *curCityLabel;

@property (strong, nonatomic)NSMutableArray *data;
@property (strong, nonatomic)NSMutableArray *showData;
@property (copy, nonatomic) NSString *cityId;

@property (assign,nonatomic) int pageNum;

@end


@implementation SelectExamPlaceViewController

//@synthesize showData;
@synthesize data;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.dataSource = self;
    
    self.tableView.delegate = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.showsVerticalScrollIndicator = FALSE;
    
    self.tableView.showsHorizontalScrollIndicator = FALSE;
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

    self.searchBar.delegate = self;
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_select_exam_place_search_bar.png"]];
    
    self.searchBar.backgroundImage = imageView.image;
    
    
    [self.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"bg_select_exam_place_search_bar_textfield"]
                                         forState:UIControlStateNormal];
    
    [self.searchBar setImage:[UIImage imageNamed:@"ico_select_exam_place_search_bar"]
            forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    
    
    self.data = [[NSMutableArray alloc] init];
    self.showData = [[NSMutableArray alloc] init];
    
    _pageNum = 1;
    
    self.cityId = [UserDataSingleton shareInstance].curCityId;
    self.curCityLabel.text = [UserDataSingleton shareInstance].cityName;
    
    [self getData];
}

- (void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    switch (tag)
    {
        case 1:
        {
            //俱乐部列表
            for (NSDictionary * dic in Response)
            {
                ClubListModel *model = [ClubListModel ClubListWithDict:dic];
                [self.data addObject:model];
                [self.showData addObject:model];
            }
            
                [self.tableView reloadData];

            break;
        }
    }
}

- (void)GetSuccessMessage:(id)message andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    NSString *mes = message;
    
    [MBProgressHUD showSuccess:mes toView:self.view];
    
//    switch (tag)
//    {
//        case 1:
//           // [MBProgressHUD showSuccess:mes toView:self.view];
//            break;
//        case 2:
//           // [MBProgressHUD showSuccess:mes toView:self.view];
//            break;
//    }
}

- (void)GetFailResponse:(id)Response andTag:(int)tag
{
    [MBProgressHUD hideHUDForView:self.view];
    
    if (Response == nil)
        return;
    
    NSString *message = Response;
    
    [MBProgressHUD showError:message toView:self.view];
}

-(void)getData
{
    [MBProgressHUD showMessage:@"正在加载"];
    
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
    NSString *pagenum = [NSString stringWithFormat:@"%d",_pageNum];
    
    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:ExamClubListInterface andParameter:@[@{
                                        @"club_city":self.cityId,
                                        @"site_name":@"",
                                        @"nowpage":pagenum,
                                        @"pagesize":@"10"}] tag:1];
}

#pragma mark 设置上下拉刷新

- (void)loadNewData
{
    [self.showData removeAllObjects];
    
    [self.data removeAllObjects];
    _pageNum = 1;

    [self getData];
    [self.tableView.header endRefreshing];
}

- (void)loadMoreData
{
    ++_pageNum;

    [self getData];
    [self.tableView.footer endRefreshing];
}

//tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.showData count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 71;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.showData count] > 0)
    {
        SelectExamPlaceCell *cell = [SelectExamPlaceCell cellWithTableView:tableView];
        
        ClubListModel *model = (ClubListModel *)[self.showData objectAtIndex:indexPath.row];
        cell.title.text = model.exam_site_name;
        cell.address.text = model.address;
        
        return cell;
    }
    
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if ([self.showData count] > 0)
    {
        ClubListModel *model = [self.showData objectAtIndex:indexPath.row];
        NSString *string = [self.curCityLabel.text stringByAppendingString:model.address];
        
        if ([self.delegate respondsToSelector:@selector(setExamPlace:Id:)]) {
            
            [self.delegate setExamPlace:string Id:model.id];
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (NSMutableArray *)searchStringForcharacter:(NSString*)searchStr
{
    NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:10];
    
    for (int i = 0; i < [self.data count]; ++i)
    {
        ClubListModel *model = (ClubListModel *)[self.data objectAtIndex:i];

        if ([model.exam_site_name hasPrefix:searchStr])
        {
            [tmp addObject:model];
        }
    }
    
    return [tmp count] > 0 ? tmp : nil;
}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    if (searchText!=nil && searchText.length > 0)
    {
        self.showData = [self searchStringForcharacter:searchText];
        
        if (!self.showData)
        {
            self.showData = [NSMutableArray arrayWithCapacity:1];
//            [self.showData addObject:@""];
        }
        
        [self.tableView reloadData];
    }
    else
    {
        self.showData = [NSMutableArray arrayWithArray:self.data];
        [self.tableView reloadData];
    }
}

-(void)configNavigationItem
{
    self.navigationItem.title = @"选择考试地点";
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.navigationController.navigationBar
     setBackgroundImage:[UIImage imageNamed:@"bg_navigation_bar"]
     forBarMetrics:UIBarMetricsDefault];
    
    //status bar的字体为白色
    //导航栏的背景色是黑色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0],UITextAttributeTextShadowColor,[UIFont fontWithName:@"Hiragino Sans GB" size:18.0],NSFontAttributeName,nil]];
    
    [self configNavigationBackAction:^{
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self configNavigationRightItemWith:[UIImage imageNamed:@"ico_select_exam_place_locate_city"] andAction:^{
        
        SearchCityViewController *obj = [SearchCityViewController create];
        obj.delegate = self;
        
        [self.navigationController pushViewController:obj animated:YES];
    }];
}

-(void)setExamCity:(NSString *)city
{
    self.curCityLabel.text = city;
    
    NSMutableArray *data1 = [UserDataSingleton shareInstance].cityList;
    
    for (int i = 0; i < [data1 count]; ++i)
    {
        CitylistModel *model = [data1 objectAtIndex:i];
        
        if (model && [model.name isEqualToString:city])
        {
            if (![self.cityId isEqualToString:model.id])
            {
                [self.data removeAllObjects];
                [self.showData removeAllObjects];
            }
            
            self.cityId = model.id;
            
            _pageNum = 1;
            
            [self getData];
            
            break;
        }
    }
}

-(void)useMethodToFindBlackLineAndHind
{
    UIImageView* blackLineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    blackLineImageView.hidden = YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self configNavigationItem];

    [self useMethodToFindBlackLineAndHind];
}

-(void)viewWillDisappear:(BOOL)animated
{

}

@end

*/









